/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package pl.cezary.butler.walili.server.db.tasks;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Czarek
 */
public class TableExistsTask extends FetchingTask<Boolean> {

    private static final Logger log = Logger.getLogger(TableExistsTask.class.getName());
    private boolean wynik = false;
    private final String tabela;

    public TableExistsTask(String tabela) {
        this.tabela = tabela;
    }

    @Override
    protected Boolean $getResultsNonLocking() {
        return wynik;
    }

    @Override
    public void executeInternal() {
        try {

            // wynik = getJdbcTemplate().queryForObject("SELECT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE upper(TABLE_NAME)=?)", Boolean.class, tabela.toUpperCase());

            Statement stmt = getDS().getConnection().createStatement();
            ResultSet rs = stmt.executeQuery(String.format("SELECT * FROM %s LIMIT 1", tabela));
            try {
                rs.next();
                wynik = true;
            } finally {
                rs.close();
                stmt.close();
            }
        } catch (Exception ex) {
            log.log(Level.SEVERE, "Błąd podczas wykonywania zapytania testującego obecność tabeli", ex);
            wynik = false;
        }
    }
}
